/*
 * @Date: 2023-04-04 09:39:47
 * @LastEditTime: 2023-04-17 11:22:47
 */
import storage from 'store'
import { login } from '@/api/login'
import { exitLogin } from '@/api/account'
const user = {
  state: {
    token: '',
    username: '',
    telephone: '',
    role: 0
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USERNAME: (state, username) => {
      state.username = username
    },
    SET_ROLE: (state, role) => {
      state.role = role
    },
    SET_TELEPHONE: (state, telephone) => {
      state.telephone = telephone
    }
  },

  actions: {
    // 登录
    Login ({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then((res) => {
            if (res.code === 200) {
              const { token, user_name, user_telephone } = res.data
              storage.set('token', token, 7 * 24 * 60 * 60 * 1000)
              storage.set('username', user_name, 7 * 24 * 60 * 60 * 1000)
              storage.set('telephone', user_telephone, 7 * 24 * 60 * 60 * 1000)

              commit('SET_TOKEN', token)
              commit('SET_USERNAME', user_name)
              commit('SET_TELEPHONE', user_telephone)
            }
            resolve(res)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 登出
    Logout ({ commit, state }) {
      return new Promise((resolve) => {
        exitLogin().then((res) => {
          if (res.code === 200) {
            commit('SET_TOKEN', '')
            commit('SET_USERNAME', '')
            commit('SET_TELEPHONE', '')
            storage.remove('token')
            storage.remove('username')
            storage.remove('telephone')
            resolve(true)
          } else {
            this.$message.error(res.msg)
            resolve(false)
          }
        })
      })
    }
  }
}

export default user
